import React, {useEffect, useRef, useState} from 'react';
import {Button, Col, Divider, Form, Input, message, Modal, Popconfirm, Select, Space, Tooltip} from 'antd';
import {connect, Dispatch} from 'umi';

import {DeleteOutlined, SafetyCertificateFilled, TeamOutlined} from '@ant-design/icons';
import ProTable from '@ant-design/pro-table';

import {ActionType, ProColumns} from '@ant-design/pro-table/lib/Table';
import {SorterResult} from 'antd/es/table/interface';
import {IResponse, ProjectListObj, RoleItem, RoleTableListItem} from '../type';
import {ConnectState} from '@/models/connect';
import './style.less';
import {deleteRole, getUserPri} from '@/services/information';
import * as dayjs from 'dayjs';
import {debounce, sortByProps, sortDate, sortString} from '@/utils/common';

const JurisdictionModel = React.lazy(() => import('./components/JurisdictionModel'));
const RelationModel = React.lazy(() => import('../components/RelationModel'));
const EditPerson = React.lazy(() => import('./components/EditPerson'));
const EditJurisdiction = React.lazy(() => import('./components/JurisdictionModel/edit'));

interface UserProps {
  dispatch: Dispatch;
  roles: Array<RoleTableListItem>;
  projectList: Array<ProjectListObj>;
  loading?: boolean;
}

const RoleList: React.FC<UserProps> = (props) => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false); // 新建角色弹框
  const [row, setRow] = useState<RoleTableListItem>(); // 操作的表格列数据
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false); // 权限管理弹框
  const [editPersonVisible, setEditPersonVisible] = useState<boolean>(false); //
  const [editJurisdictionVisible, setEditJurisdictionVisible] = useState<boolean>(false); //
  const [queryParams, setQueryParams] = useState<{}>({}); // 表格查询字段
  const [sorter, setSorter] = useState<string>('');
  const [projects, setProjects] = useState<any>([]);
  const [identityModalVisible, handleIdentityModalVisible] = useState<boolean>(false); // 关联用户
  const actionRef = useRef<ActionType>();
  let {roles, projectList, dispatch, loading} = props;


  useEffect(() => {
    getProjects()
    // 获取角色列表（表格数据）
    if (roles.length === 0) {
      dispatch({
        type: 'userManage/fetchRole',
      });
    }
    // 获取项目权限列表
    if (projectList.length === 0) {
      dispatch({
        type: 'userManage/fetchProject',
      });
    }
  }, []);
  const layout = {
    labelCol: {span: 4},
    wrapperCol: {span: 20},
  };
  // 表格配置项 包含新建弹出框
  const confirmProps = {
    title: "删除后角色成员看不到该角色中对应的看板,确认删除该角色吗？",
    okText: "确定",
    cancelText: "取消"

  };

  const delRole = (roleId: any) => {
    deleteRole(roleId).then(resp => {
      const {header = {}} = resp
      if (header.code === 200) {
        message.success('删除成功')
      }
      dispatch({
        type: 'userManage/fetchRole',
      });
    })
  }
  const columns: ProColumns<RoleTableListItem>[] = [
    {
      title: '角色名称',
      dataIndex: 'name',
      ellipsis: true,
      sorter: (a, b) => sortString(a, b, 'name'),
      rules: [
        {
          required: true,
          message: '请输入角色名称',
        },
      ],
    },
    {
      title: '项目',
      dataIndex: 'projects',
      hideInSearch: true,
      ellipsis: true,
      rules: [
        {
          required: true,
          message: '请选择归属项目',
        },
      ],
      sorter: (a, b) => sortString(a, b, 'projects'),
    },
    {
      title: '创建人',
      dataIndex: 'createBy',
      hideInForm: true,
      hideInSearch: true,
      ellipsis: true,
      render: (text: any, info: RoleTableListItem) => info.user.name,
      sorter: (a, b) => sortString(a, b, 'createBy'),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInForm: true,
      hideInSearch: true,
      sorter: (a, b) => sortDate(a, b, 'createTime'),
      renderText: (text) => {
        return dayjs(text, 'yyyy-MM-dd HH:mm:ss').format('YYYY-MM-DD');
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 138,
      render: (_: any, record: RoleTableListItem) => (
        <>
          <Space>
          <Tooltip title={'成员编辑'}>
            <TeamOutlined onClick={() => {
              setEditPersonVisible(true);
              setRow(record);
            }}/>
          </Tooltip>
          <Tooltip title={'权限编辑'}>
            <SafetyCertificateFilled onClick={() => {
              setEditJurisdictionVisible(true);
              setRow(record);
            }}/>
          </Tooltip>
          <Tooltip title={'删除角色'}>
            <Popconfirm {...confirmProps} onConfirm={() => {
              delRole(record.id)
            }}>
              <DeleteOutlined/>
            </Popconfirm>
          </Tooltip>
          </Space>
        </>
      ),
    },
  ];

  // 新建角色
  const addRole = (v: RoleItem) => {
    v.isEnable = 1;
    v.type = 1;
    dispatch({
      type: 'role/create',
      payload: v,
      callback: (response: IResponse) => {
        const {header} = response;
        if (header.code === 200) {
          message.success('新建成功');
          dispatch({
            type: 'userManage/fetchRole',
          });
        } else {
          message.warning('新建失败');
        }
        handleModalVisible(false);
      },
    });
  };

  // 获得表格滚动区域高度
  let tableScroll = 300;
  const wrapperRef = useRef<any>();

  if (wrapperRef && wrapperRef.current) {
    tableScroll = wrapperRef.current.scrollHeight - 280;
  }

  const dataSource = roles.map(item => ({
    ...item,
    projects: (item.project ? item.project.name : ''),
    createBy: (item.user ? item.user.name : ''),
    projectId: item.project.id
  }))
    .filter((value: RoleTableListItem) => {
      const keys = Object.keys(queryParams);
      if (keys.length === 0) {
        return true;
      } else {
        for (let i in keys) {
          const key = keys[i];
          if (value[key].toString().indexOf(queryParams[key]) === -1) {
            return false;
          }
        }
      }
      return true;
    }).sort((a: any, b: any) => {
      return sortByProps(a, b, {projects: "ascending", name: "ascending"})
    })
  // .sort((a,b)=>sortDate(b,a,'createTime'))
  // const debounce = (fn: any, wait:any) => {
  //   let timeout:any;
  //   return function(input: any) {
  //     input.persist();
  //     if (timeout !== null) clearTimeout(timeout);
  //     timeout = setTimeout(fn, wait, input);
  //   };
  // };
  const handleInputChange = e => {
    const {value} = e.target;
    setQueryParams({name: value});
  };

  function getProjects() {
    getUserPri().then(resp => {
      const {payload} = resp;
      if (payload && payload.length > 0) {
        let arr = payload.map((item: any) => ({value: item.projectId, label: item.projectName}));
        setProjects(arr);
      }
    });
  }

  const handleSelectChange = (v: string) => {
    if (v) {
      setQueryParams({projects: v});
    } else {
      setQueryParams({projects: ''});
    }
  };
  return (
    <div style={{height: '100%'}} ref={wrapperRef}>

      <div className={'table-toolbar'}>
        <Col span={6}>
          <Input allowClear
                 placeholder={'搜索角色'}
                 onChange={debounce(handleInputChange, 800)}
          ></Input>
        </Col>
        <Col span={6} className={'gutter-16'}>
          <Select style={{width: '100%'}}
                  placeholder={'全部项目'}
                  allowClear
                  onChange={handleSelectChange}
          >
            {projects.map((item: any, key: number) => <Select.Option value={item.label}
                                                                     key={item.value}>{item.label}</Select.Option>)}
          </Select>
        </Col>
        <Col span={11} className={'toolbar'}>
          <Button onClick={() => handleModalVisible(true)}>
            添加角色
          </Button>
        </Col>
      </div>

      <ProTable<RoleTableListItem>
        loading={loading}
        scroll={{y: tableScroll}}
        headerTitle=""
        actionRef={actionRef}
        rowKey="id"
        search={false}
        options={{
          fullScreen: false,
          reload: false,
          setting: false,
          density: false,
        }}
        params={{
          sorter,
        }}
        onChange={(_, _filter, _sorter) => {
          const sorterResult = _sorter as SorterResult<RoleTableListItem>;

          if (sorterResult.field) {
            setSorter(`${sorterResult.field}_${sorterResult.order}`);
          }
        }}
        dataSource={dataSource}
        onSubmit={(params) => {
          setQueryParams(params);
        }}
        columns={columns}
      />
      {/* 权限管理弹框 */}
      {row && updateModalVisible ? (
        <React.Suspense fallback={null}>
          <JurisdictionModel
            modalVisible={updateModalVisible}
            onCancel={() => {
              handleUpdateModalVisible(false);
            }}
            stepFormValues={row}
          />
        </React.Suspense>
      ) : null}

      {/* 关联用户弹框 */}
      {row && identityModalVisible ? (
        <React.Suspense fallback={null}>
          <RelationModel
            modalVisible={identityModalVisible}
            onCancel={() => {
              handleIdentityModalVisible(false);
            }}
          />
        </React.Suspense>
      ) : null}

      {editPersonVisible ? (
        <React.Suspense fallback={null}>
          <EditPerson
            visible={editPersonVisible}
            row={row}
            onCancel={() => {
              setEditPersonVisible(false);
            }}
          />
        </React.Suspense>
      ) : null}

      {editJurisdictionVisible ? (
        <React.Suspense fallback={null}>
          <EditJurisdiction
            roleId={row?.id}
            projectId={row?.projectId}
            visible={editJurisdictionVisible}
            onCancel={() => {
              setEditJurisdictionVisible(false);
            }}
          />
        </React.Suspense>
      ) : null}

      {/* 新建角色弹框 */}
      <Modal
        onCancel={() => handleModalVisible(false)}
        visible={createModalVisible}
        title="添加角色"
        footer={
          null
        }
      >
        <Form {...layout} name="control-hooks" onFinish={addRole}>
          <Form.Item name="name" label="角色名称：" rules={[{required: true}]}>
            <Input allowClear/>
          </Form.Item>
          <Form.Item name="projectId" label="项目：" rules={[{required: true}]}>
            <Select style={{width: '100%'}}
                    placeholder={'请选择'}
                    allowClear
                    options={projects}
            >
            </Select>
          </Form.Item>
          <Form.Item>
            <div className={'footer'}>
              <Col span={5}>
                <Button block onClick={_ => handleModalVisible(false)}>
                  取消
                </Button>
              </Col>
              <Col span={5}>
                <Button htmlType='submit'>
                  添加角色
                </Button>
              </Col>
            </div>
          </Form.Item>
        </Form>
        {/*<ProTable<RoleTableListItem, RoleItem>*/}
        {/*  onSubmit={addRole}*/}
        {/*  rowKey="key"*/}
        {/*  type="form"*/}
        {/*  columns={columns}*/}
        {/*  rowSelection={{}}*/}
        {/*/>*/}
      </Modal>
    </div>
  );
};
export default connect(({userManage, loading}: ConnectState) => ({
  roles: userManage.roles || [],
  projectList: userManage.projectList || [],
  loading: loading.effects['userManage/fetchRole'],
}))(RoleList);
